package com.atguigu.gmall.order.interceptor;

import com.atguigu.gmall.common.utils.CookieUtils;
import com.atguigu.gmall.common.utils.JwtUtils;
import com.atguigu.gmall.common.utils.RsaUtils;
import com.atguigu.gmall.order.vo.UserInfo;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;

@Component
public class LoginInterceptor  implements HandlerInterceptor {

    private static final ThreadLocal<UserInfo> THREAD_LOCAL = new ThreadLocal<>();
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String token = CookieUtils.getCookieValue(request, "GMALL-TOKEN");

        Map<String, Object> map = JwtUtils.getInfoFromToken(token, RsaUtils.getPublicKey("F://keys/rsa.pub"));
        String userId = map.get("userId").toString();
        UserInfo userInfo = new UserInfo();
        userInfo.setUserId(Long.parseLong(userId));
        THREAD_LOCAL.set(userInfo);
        return true;//登录拦截器  false表示拦截请求
    }
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        THREAD_LOCAL.remove();
    }
    public static UserInfo getUserInfo(){
        return THREAD_LOCAL.get();
    }


}
